﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;

namespace GW2LastOnline
{
    public partial class formLogin : Form
    {
        private bool closed;

        public formLogin()
        {
            InitializeComponent();
        }

        public CookieCollection Cookies
        {
            get;
            set;
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void formLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            closed = true;
        }

        private void OnLoginResult(CookieCollection cookies)
        {
            if (closed)
                return;

            if (cookies == null)
            {
                buttonSignIn.Enabled = true;
                progressLogin.Visible = false;
                labelFailed.Visible = true;
            }
            else
            {
                this.Cookies = cookies;
                this.DialogResult = DialogResult.OK;
            }
        }

        private void buttonSignIn_Click(object sender, EventArgs e)
        {
            if (textUsername.Text.Length == 0 || textPassword.Text.Length == 0)
            {
                labelFailed.Visible = true;
                if (textUsername.Text.Length == 0)
                    textUsername.Focus();
                else
                    textPassword.Focus();
                return;
            }

            buttonSignIn.Enabled = false;
            progressLogin.Visible = true;
            labelFailed.Visible = false;

            new Thread(new ThreadStart(delegate
                {
                    CookieCollection cookies = null;
                    try
                    {
                        cookies = Account.Login(textUsername.Text, textPassword.Text);
                    }
                    catch { }
                    try
                    {
                        this.BeginInvoke(new MethodInvoker(delegate
                            {
                                OnLoginResult(cookies);
                            }));
                    }
                    catch { }
                })).Start();
        }
    }
}
